async with 用于处理需要异步进行“设置”和“清理”的资源,例如数据库连接、网络会话等。

一个对象若要支持 async with,它必须实现 __aenter____aexit__ 这两个异步方法,这被称为异步上下文管理器

  • __aenter__:在进入 async with 代码块前被 await 调用,负责资源的异步初始化。

  • __aexit__:在退出代码块时被 await 调用,负责资源的异步清理。

Python

class AsyncDatabaseConnection:
    async def __aenter__(self):
        print("Connecting to DB...")
        await self.connect()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        print("Closing DB connection...")
        await self.close()

async def main():
    async with AsyncDatabaseConnection() as conn:
        # 在这里 conn 已经异步连接好了
        await conn.execute_query("...")
    # 退出代码块后,conn 会被异步关闭

相关链接: